package cn.wolfcode.thread;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.CountDownLatch;

/**
 * 闭锁
 * 计数多个线程执行完成后 再处理关键逻辑(具有先后执行顺序)
 */
public class TestCountDowmLatch {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(50);
        CountDownLatchDemo countDownLatchDemo = new CountDownLatchDemo(countDownLatch);
        Instant start = Instant.now();
        for (int i = 0; i <50 ; i++) {
            new Thread(countDownLatchDemo).start();
        }

        //这里需要阻塞,阻塞到countDown()计数为0
        countDownLatch.await();

        Instant end = Instant.now();
        Duration between = Duration.between(start, end);
        System.out.println(between);

    }
}

class CountDownLatchDemo implements Runnable{

    private CountDownLatch countDownLatch;

    public CountDownLatchDemo(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }

    public void run() {
        try {
            int sum = 0;
            for (int i = 0; i <50000 ; i++) {
                if (i%2==0){
                    sum += i;
                }
            }
            System.out.println(Thread.currentThread().getName() + sum);
        }finally {
            countDownLatch.countDown();
        }
    }
}
